<template>
  <div>
    <Top></Top>
    <Header></Header>
    <el-row>
      <!-- span:占多少栏   offset：向右偏移多少栏 -->
      <el-col :span="16" :offset="4">
        <el-row :gutter="20">
          <!-- 图片 -->
          <el-col :span="8">
            <img :src="$imgPrefix + goods.image" alt="">
          </el-col>
          <!-- 信息、操作 -->
          <el-col :span="16">
            <p><b>{{goods.name}}</b></p>
            <p><span>价格：</span>{{goods.price}}</p>
            <p><span>库存：</span>{{goods.stock}}</p>
            <el-input-number v-model="num" :min="1" :max="goods.stock" size="mini"></el-input-number>
            <el-row v-if="isConsumer()">
              <el-button type="danger">立即购买</el-button>
              <el-button type="success" @click="add">加入购物车</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
    </el-row>  
    <Footer></Footer>
  </div>
</template>

<script>
import Top from './commons/top.vue'
import Header from './commons/header.vue'
import Footer from './commons/footer.vue'

export default{
  data(){
    return{
      gid: this.$route.params.gid,
      goods: null,
      num: 1,
      user: JSON.parse(localStorage.getItem("user"))
    }
  },
  components: {
    // 2.注册
    Top,
    Header,
    Footer,
  },
  mounted(){
    this.$axios.get("/goods/findById/" + this.gid).then(res =>{
      this.goods = res.data.data
    })
  },
  methods:{
    add(){
      this.$axios.post("/cart/add",{
        gid: this.gid,
        num: this.num,
        price: this.goods.price
      }).then(res => {
        console.log(res.data)

      })
    },
    isConsumer(){
      // 得到角色列表
      if(this.user.roleList){
        for(let i = 0; i < this.user.roleList.length; i++){
          let role =this.user.roleList[i];
          if(role.name == 'consumer'){
            return true
          }
        }
        return false
      }
    }
  }
}
</script>
<style scoped>
p{
  margin-bottom: 20px;
}
</style>